package com.example.messaging;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;

import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

import com.example.xml.XMLToolkit;

public class EventCMessage extends Message {

	private ArrayList<int[]> pointList;
	private int[] point;
	private String eventType;
	private String action;

	public void setPointList(ArrayList<int[]> pointList) {
		this.pointList = pointList;
		altered = true;
	}

	public void setPoint(int[] point) {
		this.point = point;
		altered = true;
	}

	public void setEventType(String eventType) {
		this.eventType = eventType;
		altered = true;
	}
	
	public void setAction(String action) {
		this.action = action;
	}

	public ArrayList<int[]> getPointList() {
		return pointList;
	}

	public int[] getPoint() {
		return point;
	}

	public String getEventType() {
		return eventType;
	}
	
	public String getAction() {
		return action;
	}

	@Override
	public void setXML() {
		// throw new
		// UnsupportedOperationException("setXML by chtelo jeste dopsat...");
		if (!altered) {
			return;
		}

		XmlSerializer xmlSerializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();

		try {

			// form location string (if point is null, event created arrayList
			// of points, on the other hand, if pointList is null, event created
			// single point)

			String location;
			if(eventType.equals("onTouch") && action.equals("ACTION_UP")) {
				StringBuilder sb = new StringBuilder();
				int i = 0;
				for(int[] arr : pointList) {
					if(i != 0) {
						sb.append(",");
						
					}
					sb.append(arr[0]);
					sb.append(" ");
					sb.append(arr[1]);
					++i;
				}
				location = sb.toString();
			} else {
				location = point[0] + " " + point[1];
			}

			xmlSerializer.setOutput(writer);

			// TODO is encoding mentioned here right??
			// start DOCUMENT, set encoding and standalone flag
			xmlSerializer.startDocument("UTF-8", true);
			// open tag: <cln>
			xmlSerializer.startTag("", "cln");
			xmlSerializer.attribute("", "state", "event_occurred");

			// open tag: <event>
			xmlSerializer.startTag("", "event");
			xmlSerializer.attribute("", "type", eventType);
			xmlSerializer.attribute("", "location", location);
			if(eventType.equals("onTouch")) {
				xmlSerializer.attribute("", "action", action);
			}

			// close tag: </event>
			xmlSerializer.endTag("", "event");

			// close tag: </cln>
			xmlSerializer.endTag("", "cln");

			// end DOCUMENT
			xmlSerializer.endDocument();

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		xmlRep = writer.toString();
		altered = false;
	}

	@Override
	public void decodeXML(String xml) {
		// TODO Auto-generated method stub

	}
}
